const app = getApp()
import prizeApi from '../../api/prizeApi'
import prizeSendApi from '../../api/prizeSendApi'
import dateUtils from '../../util/date'
Page({

  /**
   * 页面的初始数据
   */
  data: {
   prize: {},
   winner: {},
   imgList: [],
   isJoin:false,
   joinList: [],
   shareImg: '',
   isShow: false,
   personCount: 0,

   prizeSend: '',
   isPublisher: false,

   isHidden: true,
   avatarUrl: '',
    nickname: "",

    timer:null,
    second: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    var prizeId = ''
    if (options.scene){
      var scene = decodeURIComponent(options.scene);
      prizeId = scene
    }else{
      prizeId = options.prizeId
    }

    this.init(prizeId)

    
  },

  onShow: function () {
    if( wx.getStorageSync('refreshPrizeSend')){
      this.getPrizeSend()
      wx.removeStorageSync('refreshPrizeSend')
    }
  },

  async init(prizeId){
    wx.showLoading({
      mask:true
    })
  

    await app.getOpenid()
   
    await this.getPrize(prizeId)

    await Promise.all([
      this.getIsJoin(),
      this.getPersonCount(),
      this.getWinner(),
      this.getIsPublisher(),
      this.getPrizeSend(),
    ])
    
    this.setData({
      isHidden: false
    })


    wx.hideLoading( )
  },

  async getPrize(prizeId){
   
    let data = await  prizeApi.getPrize(prizeId)
   
    let date = dateUtils.createDate(data.date)
    let offsetSec = Math.floor((date.getTime() - new Date().getTime()) / 1000) 

    this.countDown(offsetSec + 10)
    this.setData({
      prize : data,
      imgList: data.imgList
    })


    //创建分享图
    //   app.createShareImg(this.data.prize).then(path => {
    //     this.setData({
    //       shareImg: path
    //     });
    //   })
  },

  countDown(sec){
    console.log(sec)
    console.log(dateUtils.secondToStr(sec))
    this.setData({
      second: dateUtils.secondToStr(sec)
    })
    if(sec < 0){
      return
    }
   
    this.data.timer = setTimeout(() => {
        sec --
        if(sec == 0) {
          this.init(this.data.prize._id)
        }
        this.countDown(sec)
    }, 1000);
  },

  
  onChooseAvatar(e){
    if(this.data.nickname){
      this.join()
      return
    }
    this.selectComponent('#avatarNickname').open()
   
  },
  avatarNicknameConfirm(e){
    console.log(e)
    this.setData({
      avatarUrl: e.detail.avatarUrl,
      nickname: e.detail.nickname,
    })
    this.join()
  },


  toJoin(){
     // 抽奖结果通知
     wx.requestSubscribeMessage({
      tmplIds: ['Khz0Mi5ts0GWvU8NeN4AFtC-iuyvpS6nY5XOFM3eCbU'],
      success (res) { }
    })

    
    wx.showLoading({
      title: '加载中',
      mask: true
    })

   
    wx.getUserProfile({
      desc: '用于抽奖中人员的显示',
      success: (res) => {
        console.log('用户信息授权',res)
        
        const userInfo = res.userInfo;
        if(userInfo){  
          wx.setStorageSync('authorizedInfo', res)
          wx.setStorageSync('userInfo', userInfo)
          app.globalData.userInfo = userInfo
          this.join()
        }
      },
      fail (e) {
       
      },
      complete(){
        wx.hideLoading();
      }
    })
    
    
  },

  async join(){
    
    wx.showLoading({
      mask:true
    })
   

    
    await prizeApi.joinPrize({
      openid: wx.getStorageSync('openid'),
      nickName: this.data.nickname,
      avatarUrl: this.data.avatarUrl,
      prizeId: this.data.prize._id
    })

    this.getIsJoin()
    this.getPersonCount()
    wx.hideLoading()

    wx.showToast({
      title: '已参与',
      icon: 'success'
    })
   
  },

  async getIsJoin(){
   
    let res = await prizeApi.getIsJoin({
      openid: wx.getStorageSync('openid'),
      prizeId: this.data.prize._id
    })
    
    this.setData({
      isJoin: res.length > 0
    })
  },

  async getPersonCount(){
    let res = await prizeApi.getPersonCount({
      prizeId: this.data.prize._id
    })
    this.setData({
      personCount: res
    })
  },

  toPersonList(){
    wx.navigateTo({
      url: '/prize/personList/personList?prizeId=' + this.data.prize._id,
    })
  },

  async getWinner(){
    let res = await prizeApi.getWinner({
      prizeId: this.data.prize._id
    })
    
    if(res.length > 0){
      this.setData({
        winner: res[0]
      })
    }
    
  },

  async getProduct(){
   
    if(this.data.winner.openid == wx.getStorageSync('openid')){
      wx.navigateTo({
        url: '/prize/getPrize/getPrize?prizeId=' + this.data.prize._id,
      })
    } else {
      wx.showToast({
        title: '您不是中奖人',
        icon: 'none'
      })
    }
  },

  lookImg(e){
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.prizeSend.imgList,
      current: url
    })
  },

  async getIsPublisher(){
   
    this.setData({
      isPublisher: wx.getStorageSync('openid') == this.data.prize.openid
    })
  },

  async getPrizeSend(){
    
    let list = await prizeSendApi.getPrizeSend({
        prizeId: this.data.prize._id,
    })
    
    if(list.length > 0){
        this.setData({
          prizeSend: list[0],
        })
    } 
  },

  toSend(){
    wx.navigateTo({
      url: '/prize/sendPrize/sendPrize?prizeId=' + this.data.prize._id,
    })
  },
  
  previewImage(e){
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgList,
      current: url
    })
  },
 
  getWXACode(){
    app.getWXACode({
      path:'prize/prizeDetail/prizeDetail',
      scene:this.data.prize._id
    }).then(res => {
      
    })
  },
  toShare(){
    wx.setStorageSync("prize", this.data.prize)
    wx.navigateTo({
      url: '/pages/share/share',
    })
  },

  copyContent(){
    wx.setClipboardData({
      data: this.data.prizeSend.content,
      success (res) {
        
      }
    })
  },

 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
   
      var obj = {
        title: this.data.prize.content,
        path: "/prize/prizeDetail/prizeDetail?prizeId="+this.data.prize._id
      }
      if(this.data.imgList.length > 0){
        obj.imageUrl = this.data.imgList[0]
      }
  
    
    return obj
  },

  onShareTimeline: function () {
    
       var obj = {
         title: this.data.prize.content,
         query: "prizeId="+this.data.prize._id
       }
       if(this.data.imgList.length > 0){
         obj.imageUrl = this.data.imgList[0]
       }

     
     return obj
   }
})